import { createRouter, createWebHistory } from 'vue-router'
import { h } from 'vue'
import Layout from '../views/Layout.vue'
import { getUserMenu } from '../api/permission'
import { ElMessage } from 'element-plus'

// 静态路由，不需要权限校验的路由
const constantRoutes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/register',
    component: () => import('../views/Register.vue'),
    meta: { requiresAuth: false }
  }
]

// 基础路由，需要登录但不需要动态判断权限的路由
const baseRoutes = [
  {
    path: '/',
    component: Layout,
    meta: { requiresAuth: true },
    redirect: '/home',
    children: [ // 嵌套子路由
      {
        path: 'home',
        name: 'Home',
        component: () => import('../views/Home.vue'),
        meta: { title: '首页', requiresAuth: true }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('../views/profile/Profile.vue'),
        meta: { title: '个人信息', requiresAuth: true }
      }
    ]
  },
  // 添加系统管理模块
  {
    path: '/system',
    component: Layout,
    meta: { requiresAuth: true },
    redirect: '/system/user',
    children: [
      {
        path: 'user',
        name: 'User',
        component: () => import('../views/system/User.vue'),
        meta: { title: '用户管理', requiresAuth: true }
      },
      {
        path: 'role',
        name: 'Role',
        component: () => import('../views/system/Role.vue'),
        meta: { title: '角色管理', requiresAuth: true }
      },
      {
        path: 'permission',
        name: 'Permission',
        component: () => import('../views/system/Permission.vue'),
        meta: { title: '权限管理', requiresAuth: true }
      },
      {
        path: 'log',
        name: 'Log',
        component: () => import('../views/system/Log.vue'),
        meta: { title: '操作日志', requiresAuth: true }
      },
      {
        path: 'notice',
        name: 'Notice',
        component: () => import('../views/system/Notice.vue'),
        meta: { title: '通知公告', requiresAuth: true }
      }
    ]
  }
]

// 组件映射表
const componentMap = {
  // 系统模块
  'system/user': () => import('../views/system/User.vue'),
  'system/role': () => import('../views/system/Role.vue'),
  'system/permission': () => import('../views/system/Permission.vue'),
  'system/log': () => import('../views/system/Log.vue'),
  'system/notice': () => import('../views/system/Notice.vue'),
  // 首页和个人中心
  'home': () => import('../views/Home.vue'),
  'profile': () => import('../views/profile/Profile.vue')
}

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes: [...constantRoutes, ...baseRoutes]
})

// 将后端返回的菜单转换为路由
const generateRoutes = (menus) => {
  // 递归处理菜单
  const processMenu = (menu) => {
    // 标准化路径格式
    const normalizePath = (path) => {
      // 确保以/开头
      return path.startsWith('/') ? path : `/${path}`;
    };

    // 提取组件路径
    const getComponentPath = (path) => {
      // 移除开头的/
      const trimmedPath = path.startsWith('/') ? path.substring(1) : path;
      return trimmedPath;
    };

    // 如果有子菜单
    if (menu.children && menu.children.length > 0) {
      const subRoutes = [];
      
      // 处理子菜单
      menu.children.forEach(child => {
        const childRoute = processMenu(child);
        if (childRoute) {
          subRoutes.push(childRoute);
        }
      });

      // 跳过没有有效子菜单的菜单
      if (subRoutes.length === 0) {
        return null;
      }

      // 处理当前菜单路径
      const fullPath = normalizePath(menu.path);
      
      // 构造和返回路由配置
      return {
        path: fullPath,
        name: menu.name || `menu-${menu.id}`,
        component: Layout,
        redirect: subRoutes[0].path,
        meta: { title: menu.title, requiresAuth: true },
        children: subRoutes
      };
    } else {
      // 叶子节点 - 没有子菜单
      const fullPath = normalizePath(menu.path);
      const componentPath = getComponentPath(menu.path);
      
      // 获取对应的组件
      const component = componentMap[componentPath];
      
      // 如果没有找到组件，则跳过
      if (!component) {
        console.warn(`路由组件 ${componentPath} 未找到，可用的组件有:`, Object.keys(componentMap));
        return null;
      }
      
      // 返回路由配置
      return {
        path: fullPath,
        name: menu.name || `menu-${menu.id}`,
        component,
        meta: { title: menu.title, requiresAuth: true }
      };
    }
  }
  
  // 处理每个菜单项并添加到路由
  const newRoutes = []
  menus.forEach(menu => {
    const route = processMenu(menu)
    if (route) {
      // 正确地将路由添加到Vue Router
      router.addRoute(route)
      newRoutes.push(route)
    }
  })
  
  console.log('添加的动态路由:', newRoutes)
  return newRoutes
}

// 是否已加载动态路由
let isRoutesLoaded = false

// 路由守卫
router.beforeEach(async (to, from, next) => {
  if (to.path === '/login' || to.path === '/register') {
    // 如果要前往的路径是登录页面或注册页面，则直接放行
    next()
  } else {
    // 否则检查用户是否已登录
    const token = localStorage.getItem("token")
    if (!token) {
      // 如果未登录，则重定向到登录页面
      next("/login")
    } else {
      // 查找路由是否已存在，避免重复添加
      const hasRoute = router.hasRoute(to.name)
      if (hasRoute || isRoutesLoaded) {
        // 如果路由已存在或动态路由已加载，直接放行
        next()
      } else {
        // 动态路由，如果没有加载过，则去加载
        try {
          // 确保使用最新的token
          const currentToken = localStorage.getItem("token")
          if (!currentToken) {
            next('/login')
            return
          }

          // 延迟一下，确保token已被正确应用
          return new Promise(resolve => {
            setTimeout(async () => {
              try {
                // 获取用户菜单
                const res = await getUserMenu()
                
                // 生成路由并添加
                if (res && res.data && res.data.length > 0) {
                  generateRoutes(res.data)
                  isRoutesLoaded = true
                  
                  // 确保路由添加完成后，再进行导航（避免刷新页面找不到路由）
                  // 注意：如果当前路由无法匹配，重定向到首页
                  if (to.path === '/') {
                    next('/home')
                  } else {
                    // 添加路由后，需要重新导航，因为添加的路由不会立即生效
                    next({ ...to, replace: true })
                  }
                } else {
                  console.warn('没有获取到菜单数据')
                  next('/home')
                }
                resolve()
              } catch (error) {
                console.error('获取路由失败:', error)
                ElMessage.error('获取菜单失败，请重新登录')
                localStorage.removeItem('token')
                localStorage.removeItem('user')
                next('/login')
                resolve()
              }
            }, 300)
          })
        } catch (error) {
          console.error('路由加载错误:', error)
          next('/login')
        }
      }
    }
  }
})

export default router 